package com.czk.framework;

import com.czk.protocol.dubbo.DubboProtocol;
import com.czk.protocol.http.HttpProtocol;
import com.czk.register.ConsumerRegisterCache;
import com.czk.register.ZookeeperRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 创建代理对象
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/14 17:56
 */
public class ProxyFactory {
    public static <T> T getProxy(Class interfaceClass, String protocol) {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("进入代理方法执行了=====");
                // HttpClient httpClient=new HttpClient();
                //  NettyClient nettyClient=new NettyClient();
                Protocol protocolUsed = null;
                if (Objects.equals(protocol, "http")) {
                    protocolUsed = new HttpProtocol();
                } else if (Objects.equals("dubbo", protocol)) {
                    protocolUsed = new DubboProtocol();
                } else {
                    // 默认实现
                    protocolUsed = new HttpProtocol();
                }
                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);
                try {
                    // URL url = RemoteRegister.random(interfaceClass.getName());
                    // 先从本地缓存中获取(第一次从zookeeper中获取，然后缓存到本地)
                    // 这里由于没有起zookeeper，暂且模拟本地缓存
                    List<URL> list=new ArrayList<>();
                    list.add(new URL("localhost",8080));
                    ConsumerRegisterCache.UrlCache.put(interfaceClass.getCanonicalName(),list);
                    List<URL> cacheList = ConsumerRegisterCache.UrlCache.get(interfaceClass.getCanonicalName());
                    // 判空
                    if (cacheList == null || cacheList.size() == 0) {
                        // 从zookeeper中拉取
                        cacheList = ZookeeperRegister.get(interfaceClass.getName());
                    }
                    // 随机负载均衡
                    // int i = ThreadLocalRandom.current().nextInt(2);
                    // 拿到url
                    int i=0;
                    if (protocol=="dubbo"){
                        i=0;
                    }
                    URL url = cacheList.get(i);
                    String s = protocolUsed.send(url, invocation);
                    return s;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }
}
